import sys

class AT3Node:
    def __init__(self,hostname, publicip, privateip, kstemplate):
        self.hostname=hostname
        self.publicip=publicip
        self.privateip=privateip
        self.kstemplate=kstemplate
    
class AT3Cfg:
    def __init__(self):
        self.nodes={}
        self.rolelist=["HEAD","NFS","LDAP","PROXY", "CONDORHEAD","XROOTD","INTERACTIVE","WORKER"]
        self.cfglist={}

    def addNode(self,role, hostname,  publicip, privateip,  kstemplate):
        if not role in self.rolelist:
            raise RuntimeError("Role %s not in the predefined role list %s"%(str(role),str(self.rolelist)))

        self.nodes[role]=[AT3Node(hostname,publicip,privateip,kstemplate)]

    def addManyNodes(self, role, nnodes, hostnamepattern, publicipstarts, privateipstarts, kstemplate):
        if not role in self.rolelist:
            raise RuntimeError("Role %s not in the predefined role list %s"%(str(role),str(self.rolelist)))
        self.nodes[role]=[]
        for i in range(1,nnodes+1):
            hostname=hostnamepattern%i
            if not publicipstarts is None:
                publicip=self.getip(publicipstarts,i)
            else:
                publicip=None
            if not privateipstarts is None:
                privateip=self.getip(privateipstarts,i)
            else:
                privateip=None
            self.nodes[role].append(AT3Node(hostname,publicip,privateip,kstemplate))

    def set(self,name,value):
        self.cfglist[name]=value

    def get(self,name):
        if not self.cfglist.has_key(name):
            raise RuntimeError("configuration with name=%s does not exist"%name)
        return self.cfglist[name]
        
    def getip(self,ipstarts,n):
        spip=ipstarts.split(".")
        spip[3]=str(int(spip[3])+n)
        if int(spip[3])>=255:
            raise RuntimeError("IP address out of range %s + %s"%(ipstarts,str(n)))

        
def AT3_GenerateAllKS(cfg):
    for irole in cfg.rolelist:
        nodes=cfg.nodes[irole]
        for inode in nodes:
            #build the list of variables
            rlist={}
            for ikey in cfg.cfglist.keys():
                rlist[ikey]=cfg.cfglist[ikey]
            rlist["PUBLICIP"]=inode.publicip
            rlist["PRIVATEIP"]=inode.privateip
            rlist["HOSTNAME"]=inode.hostname

            #open template
            inf=open(inode.kstemplate,"r")
            tmpstr=inf.read()
            inf.close()

            #write output
            ouf=open("kickstart-%s.cfg","w")
            ouf.write(tmpstr%rlist)
            ouf.close()

            
            
    
